package com.enki.cigarettes.controller;

import com.enki.cigarettes.controller.vo.response.UserSignInResponseVo;
import com.enki.cigarettes.entity.BalanceHistoryT;
import com.enki.cigarettes.entity.SignInRuleT;
import com.enki.cigarettes.entity.UserSignInT;
import com.enki.cigarettes.entity.UserT;
import com.enki.cigarettes.enums.BalanceEnums;
import com.enki.cigarettes.handler.Response;
import com.enki.cigarettes.repository.BalanceHistoryTRepository;
import com.enki.cigarettes.repository.SignInRuleTRepository;
import com.enki.cigarettes.repository.UserSignInTRepository;
import com.enki.cigarettes.repository.UserTRepository;
import com.enki.cigarettes.statics.StaticKeys;
import com.enki.cigarettes.utils.PrimaryKey;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.controller
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 用户签到数据层
 * @date 2019-08-09
 */
@RestController
@RequestMapping("/api/user/signs")
@Slf4j
public class UserSignInController {

    @Autowired
    UserSignInTRepository userSignInTRepository;
    @Autowired
    BalanceHistoryTRepository balanceHistoryTRepository;
    @Autowired
    UserTRepository userTRepository;
    @Autowired
    SignInRuleTRepository signInRuleTRepository;

    @ApiOperation(value = "获取签到列表")
    @GetMapping
    public Object findItems(HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            Map<String, Object> responseData = new HashMap<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMd");
            // 获取前月的第一天
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            //将小时至0
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            //将分钟至0
            calendar.set(Calendar.MINUTE, 0);
            //将秒至0
            calendar.set(Calendar.SECOND, 0);
            //将毫秒至0
            calendar.set(Calendar.MILLISECOND, 0);
            //获得当前月第一天
            Date startTime = calendar.getTime();
            Sort sort = new Sort(Sort.Direction.ASC, StaticKeys.SORT_CREATE_TIME);
            List<UserSignInT> beanList = userSignInTRepository.findByUserTIdAndSignInTimeGreaterThanEqual(sessionId.toString(), startTime, sort);
            List<UserSignInResponseVo> signInItems = new ArrayList<>();
            for (UserSignInT bean : beanList) {
                UserSignInResponseVo signInItem = new UserSignInResponseVo();
                signInItem.setId(bean.getId());
                signInItem.setSignInTime(sdf.format(bean.getSignInTime()));
                signInItem.setSignInStatus(true);
                signInItems.add(signInItem);
            }
            responseData.put("signInItems", signInItems);
            // 检测当天是否已签到
            Calendar cale = Calendar.getInstance();
            cale.setTime(new Date());
            cale.set(Calendar.HOUR_OF_DAY, 0);
            cale.set(Calendar.MINUTE, 0);
            cale.set(Calendar.SECOND, 0);
            Date zero = cale.getTime();
            UserSignInT userSignIn = userSignInTRepository.findFirstByUserTIdAndSignInTimeGreaterThanAndSignInTimeLessThan(sessionId.toString(), zero, new Date());
            if (userSignIn != null) {
                responseData.put("signInStatus", true);
            } else {
                responseData.put("signInStatus", false);
            }
            // 计算签到获取的金额
            List<Object> signInRebate = balanceHistoryTRepository.sumBalanceByUserId(sessionId.toString(), BalanceEnums.BalanceStatus.SIGN_IN.getStatus());
            int signInAmount = 0;
            if (signInRebate.get(0) != null && signInRebate.size() != 0) {
                signInAmount = Integer.valueOf(signInRebate.get(0).toString());
            }
            responseData.put("signInAmount", signInAmount);
            return Response.success(responseData, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取签到列表失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取签到列表失败");
        }
    }

    @ApiOperation(value = "签到")
    @PostMapping
    @Transactional
    public Object save(HttpSession session) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            UserT userBean = userTRepository.findOneById(sessionId.toString());
            if (userBean == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date zero = calendar.getTime();
            UserSignInT userSignIn = userSignInTRepository.findFirstByUserTIdAndSignInTimeGreaterThanAndSignInTimeLessThan(sessionId.toString(), zero, new Date());
            if (userSignIn != null) {
                return Response.badRequest_400("当天已签到");
            }
            // 保存签到信息
            UserSignInT bean = new UserSignInT();
            bean.setId(PrimaryKey.get().toString());
            bean.setUserTId(sessionId.toString());
            bean.setSignInTime(new Date());
            bean.setIsLogin(true);
            bean.setSum(1);
            bean.setMaxCount(1);
            bean.setCreateTime(new Date());
            userSignInTRepository.save(bean);
            // 随机获取金额
            int rebate = 188;
            SignInRuleT signInRule = signInRuleTRepository.findFirstByRemoved(StaticKeys.REMOVED);
            if(signInRule != null) {
                Random ra = new Random();
                rebate = ra.nextInt(signInRule.getMaximum() - signInRule.getMinimum() + 1) + signInRule.getMinimum();
            }
            // 余额变化，金额单位为分
            // 处理用户余额
            int curBalance = userBean.getCurBalance() + rebate;
            userBean.setCurBalance(curBalance);
            // 记录余额变化历史
            BalanceHistoryT balanceHistory = new BalanceHistoryT();
            balanceHistory.setId(PrimaryKey.get().toString());
            balanceHistory.setBalanceAmountTotal(curBalance);
            balanceHistory.setBalanceStatus(BalanceEnums.BalanceStatus.SIGN_IN.getStatus());
            balanceHistory.setSubTotal(rebate);
            balanceHistory.setUserTId(userBean.getId());
            balanceHistory.setRemark("来自" + sdf.format(new Date()) + "签到");
            balanceHistory.setCreateTime(new Date());
            userTRepository.save(userBean);
            balanceHistoryTRepository.save(balanceHistory);
            return Response.success(rebate, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取签到列表失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取签到列表失败");
        }
    }
}
